package com.zhou.gulimall.product.web;

import com.zhou.gulimall.product.entity.CategoryEntity;
import com.zhou.gulimall.product.service.CategoryService;
import com.zhou.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //todo 查出所有的一级分类
        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Category();

        model.addAttribute("data",categoryEntityList);
        return "index";
    }

    //查出对应的二级三级分类
    @ResponseBody
    @GetMapping("index/catalog.json")
    //index/catalog.json
    public Map<String, List<Catelog2Vo>> getCatalogJson(){

        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();


        return map;
    }

    /**
     * redisson实现分布式锁
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.调用getLock获取到一把锁，只要锁名一样，就是同一把锁
        RLock myLock = redissonClient.getLock("myLock");
        //2.加锁
        //最佳实战 myLock.lock(30,TimeUnit.SECONDS);指定一个大一点的过期时间，将不会提供看门狗续期，提升性能。手动解锁
        myLock.lock();//阻塞式等待。。
        //1).redisson默认设置一个锁的过期时间30s，并提供锁的自动续期（看门狗）
        try{
            System.out.println("加锁成功执行业务。。。。。。"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e) {

        }finally
        {
            //3.解锁
            myLock.unlock();
            System.out.println("释放锁。。。。"+Thread.currentThread().getId());
        }
        return "hello";
    }

    /**
     * redisson实现读写锁
     * @return
     */

    @ResponseBody
    @GetMapping("/write")
    public String writeValue(){
        //利用redissonClient的getReadWriteLock方法创建一个读写锁
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        //在读写锁下面剥离一个写锁
        RLock rLock = lock.writeLock();
        //加写锁  ==》排他性(互斥)
        rLock.lock();
        try {
           s = UUID.randomUUID().toString();
            Thread.sleep(20000);
            redisTemplate.opsForValue().set("writeValue",s);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //只有当写锁释放时，读锁才能获取
            rLock.unlock();
        }
        return s;
    }

    /**
     * 读写锁
     * 读+读：相当于无锁状态，并发读都会加锁成功
     * 读+写： 等待读锁释放，写锁才能获取
     * 写+读： 等待写锁释放，读锁才能获取
     * 写+写： 阻塞。。一替一个来
     * 只要有写的存在，都必须等待。
     * @return
     */
    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        //加读锁 ==》共享性
        //在同一个读写锁下面剥离一个读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
          s = redisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }
    /**
     * redisson信号量
     * 可以用作分布式限流
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        //park.acquire(); 获取一个信号 阻塞式 成功往下走，失败继续等
        //park.tryAcquire();异步式 无论成功或失败立即给出一个Boolean
        boolean b = park.tryAcquire();
        if (b){
            //执行业务
            return "做你想做的！";
        }else {
            return "当前访问量太大，请稍后再试";
        }
    }
    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();//释放一个信号 阻塞式 成功往下走，失败继续等

        return "ok";
    }


    /**
     * 闭锁
     */
    @GetMapping("/lockdoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        //创建闭锁
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);//5个闭锁 记数
        door.await();//等待闭锁完成
        return "闭锁全部";
    }
    @GetMapping("/golockdoor/{id}")
    @ResponseBody
    public String goLockDoor(@PathVariable("id") Long id){
        //创建闭锁
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//记数-1 完成一个闭锁
        return id+"闭锁";
    }
}
